package com.kangfu.wechat.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.kangfu.common.constant.CacheConstant;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.common.utils.RedisUtils;
import com.kangfu.wechat.bean.result.Token;
import com.kangfu.wechat.utils.JsonUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenApi extends BaseApi {


    public static RedisUtils redisUtils;

    private static final Logger logger = LoggerFactory.getLogger(TokenApi.class);

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils){
        TokenApi.redisUtils = redisUtils;
    }

    /**
     * 获取access_token
     * @param appid
     * @param secret
     * @return Token
     */
    public static Token getToken(String appid, String secret) {
        //先去redis里面查有没有，没有就去请求接口
        Token token = JsonUtil.parseObject(JsonUtil.toJSONString(redisUtils.get(CacheConstant.WECHAT_ACCESS_TOKEN)), Token.class);
        if (token != null) {
            return token;
        }
        //拼接url
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("grant_type","client_credential");
        map.put("appid",appid);
        map.put("secret",secret);
        String url = BaseApi.parseParams(BaseApi.BASE_URI + "/cgi-bin/token", map);

        OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
        Request request = new Request.Builder().url(url).build(); // 创建一个请求
        try {
            Response response = okHttpClient.newCall(request).execute(); // 返回实体
            if (response.isSuccessful()) { // 判断是否成功
                String string = response.body().string();
                logger.info("获取微信access_token response: " + string);
                token = JsonUtil.parseObject(string, Token.class);
                if (token == null) {
                    throw new BusinessException("获取微信access_token 失败");
                }
                token.setExpires_in(token.getExpires_in() - 120);//防止过期的时候，redis没即时清理掉这个key
                //将token存入redis
                redisUtils.set(CacheConstant.WECHAT_ACCESS_TOKEN, token, Long.valueOf(String.valueOf(token.getExpires_in())));
                return token;
            }else {
                logger.error("获取微信access_token 失败 : code : " + response.code() + " || message : " + response.message()) ;
                throw new BusinessException("获取微信access_token 失败");
            }
        } catch (JsonProcessingException e) {
            logger.error("获取微信access_token 失败 : json 解析失败");
            throw new BusinessException("获取微信access_token 失败");
        } catch (IOException e) {
            logger.error("获取微信access_token 失败 : " + e.getMessage());
            throw new BusinessException("获取微信access_token 失败");
        }
    }

}
